// Copyright 2012 Google Inc. All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// access data & methods from background.js
var brain = chrome.extension.getBackgroundPage().brain;

// set up handlers, to comply with CSP
document.getElementById('fetchButton').addEventListener('click', onRefreshClick);

function dumpRelationships() {
  var text = '';
  if (! brain.domainMap) {
    text = "Sorry, pubs and advertisers weren't fetched successfully.";
  } else {
    var pubID, advID, pubName, advName;
    for (var domain in brain.domainMap) {
      text = text + '\n\nSITE: ' + domain + '\n';
      var relArray = brain.domainMap[domain];
      var l = relArray.length;
      for (var i = 0; i < l; i++) {
        pubID = relArray[i].pubID;
        advID = relArray[i].advID;
        pubName = brain.publishers[pubID].name;
        advName = brain.advertisers[advID].name;
        text = text + '\n    ' + pubName + ' (K' + pubID + ')'
               + ' -- affiliated with ' + advName + ' (K' + advID + ')';
      }
    }
  }
  var relArea = document.getElementById('relArea');
  brain.deleteChildren(relArea);
  relArea.appendChild(document.createTextNode(text));
  console.log(text);
}

function onRefreshClick() {
  brain.buildData(dumpRelationships);
}

dumpRelationships();
